# Copyright (c) 2011 Juan Manuel Borges Caño

import bpy, mathutils, math

def export_jmbcmaterial(context, filepath, use_some_setting):

	stream = open(filepath, 'w')

	scene = bpy.context.scene
	world = scene.world
	material = bpy.context.active_object.active_material

	# Properties

	stream.write('properties\n')
	stream.write('texture %s\n' % material.active_texture.name)
	stream.write('alpha %s\n' % material.alpha)
	ambient = material.ambient * world.ambient_color
	stream.write('ambient %s %s %s\n' % (ambient[0], ambient[1], ambient[2]))
	stream.write('diffuse %s %s %s\n' % (material.diffuse_color[0], material.diffuse_color[1], material.diffuse_color[2]))
	stream.write('specular %s %s %s\n' % (material.specular_color[0], material.specular_color[1], material.specular_color[2]))
	stream.write('emission %s %s %s\n' % (material.emit, material.emit, material.emit))
	stream.write('shininess 0.0\n')

	# Frames

	stream.write('frames 1\n')
	stream.write('matrix 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0\n')

	# Actions

	stream.write('actions 1\n')
	stream.write('name none\n')
	stream.write('start 0\n')
	stream.write('frames 1\n')

	stream.close()

	return {'FINISHED'}


from bpy_extras.io_utils import ExportHelper
from bpy.props import StringProperty


class ExportJMBCMaterial(bpy.types.Operator, ExportHelper):
	'''Export to juanmabc Material format.'''

	bl_idname = "export.material"
	bl_label = "Export juanmabc Material"
	filename_ext = ".material"
	filter_glob = StringProperty(default="*.material", options={'HIDDEN'})

	@classmethod
	def poll(cls, context):
		return context.active_object != None

	def execute(self, context):
		return export_jmbcmaterial(context, self.filepath, None)


def menu_func_export(self, context):
	self.layout.operator(ExportJMBCMaterial.bl_idname, text="Export to juanmabc Material format.")


def register():
	bpy.utils.register_class(ExportJMBCMaterial)
	bpy.types.INFO_MT_file_export.append(menu_func_export)


def unregister():
	bpy.utils.unregister_class(ExportJMBCMaterial)
	bpy.types.INFO_MT_file_export.remove(menu_func_export)


if __name__ == "__main__":
	register()
	bpy.ops.export.material('INVOKE_DEFAULT')
